package com.mayisoftware.mayioa.business.staff.impl.task;

import com.mayisoftware.mayioa.business.staff.api.domain.StaffInfo;
import com.mayisoftware.mayioa.business.staff.api.domain.StaffUploadInfo;
import com.mayisoftware.mayioa.business.staff.api.service.IStaffUploadService;
import com.mayisoftware.mayioa.business.staff.impl.dao.StaffViewMapper;
import com.mayisoftware.mayioa.common.impl.utils.ExcelReadWriteUtils;
import com.mayisoftware.mayioa.common.impl.utils.file.FileUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Component("staffFileParseTask")
public class StaffFileParseTask {

    private static final Logger log = LoggerFactory.getLogger(StaffFileParseTask.class);


    @Autowired
    private StaffViewMapper staffMapper;


    @Autowired
    private IStaffUploadService uploadService;


    public void parseStaffFiles() {
        try {
            //查询数据库记录
            List<StaffUploadInfo> staffUploadInfos = uploadService.queryRecordListNeedParse();

            if (CollectionUtils.isEmpty(staffUploadInfos)) {
                return;
            }

            String errorFilePath = "";
            for (StaffUploadInfo record : staffUploadInfos) {
                boolean isOk = true;
                StaffUploadInfo updateRecord = new StaffUploadInfo();
                try {
                    log.info("处理记录 id: {} 文件:{}", record.getImportId(), record.getFilePath());
                    String filePath = record.getFilePath();
                    File file = new File(filePath);
                    if (!file.exists() || !file.isFile()) {
                        log.error("处理记录 id: {} 文件:{}不存在", record.getImportId(), record.getFilePath());
                        continue;
                    }

                    String fileName = file.getName();
                    String fileDir = file.getParentFile().getAbsolutePath();
                    String fileNameNoExt = fileName.substring(0, fileName.lastIndexOf("."));
                    errorFilePath = fileDir + File.separator + fileNameNoExt + ".log";

                    updateRecord.setImportId(record.getImportId());
                    //更新DB状态 正在解析
                    updateRecord.setParseStatus("2");

                    uploadService.editInputRecord(updateRecord);

                    isOk = analysisOneFile(filePath,errorFilePath);
                } catch (Exception e) {
                    log.error("处理记录 id: {} 文件:{},异常", record.getImportId(), record.getFilePath(), e);
                } finally {
                    try {
                        if (isOk) {
                            log.info("处理记录 id: {} 文件:{},处理成功", record.getImportId(), record.getFilePath());
                            //更新DB状态 正在解析
                            updateRecord.setParseStatus("3");
                            uploadService.editInputRecord(updateRecord);
                        } else {
                            log.info("处理记录 id: {} 文件:{},处理失败", record.getImportId(), record.getFilePath());
                            String msg = String.format("处理记录 id: %d 文件:%s,处理失败", record.getImportId(), record.getFilePath());
                            //更新DB状态 正在解析
                            FileUtils.writeLog(errorFilePath,msg);
                            updateRecord.setParseStatus("4");
                            updateRecord.setErrorPath(errorFilePath);
                            uploadService.editInputRecord(updateRecord);
                        }
                    } catch (Exception e) {
                        log.info("处理记录状态异常", e);
                    }
                }
            }
        } catch (Exception e) {
            log.error("执行计划解析异常", e);
        }

//        log.info("结束执行计划解析");
//        poolManualService.modifyPoolInfoToCacl();
    }


    /**
     * 统计分析主方法
     *
     * @param filePath TM文件路径
     * @return 0：成功，-1：失败
     */
    private boolean analysisOneFile(String filePath,String errorFilePath) {
        File pathFile = new File(filePath);

        StaffUploadInfo staffUploadInfo = new StaffUploadInfo();
        staffUploadInfo.setFileName(pathFile.getAbsolutePath());
        if (!check(staffUploadInfo,errorFilePath)) {
            String msg = "解析文件失败。。。";
            log.error(msg);
            FileUtils.writeLog(errorFilePath,msg);
            return false;
        }
        return true;
    }

    public boolean check(StaffUploadInfo staffInfo,String errorFilePath) {

        try {
            List<StaffInfo> staffs = getStaffInfos(staffInfo,errorFilePath);

            if (CollectionUtils.isEmpty(staffs)) {
                return false;
            }

            for (StaffInfo hc : staffs) {
                int existCount = staffMapper.isStaffExist(hc);
                if (existCount == 0) {
                    staffMapper.insertStaff(hc);
                }
            }

        } catch (Exception ex) {
            FileUtils.writeLog(errorFilePath,"入库异常，请检查服务器数据库是否正确运行。");
            log.error(ex.getMessage());
            return false;
        }

        return true;
    }


    private List<StaffInfo> getStaffInfos(StaffUploadInfo uploadInfo,String errorFilePath) {
        List<StaffInfo> retList = new ArrayList<>();
        File detailFile = new File(uploadInfo.getFileName());
        List<String> contents = null;
        try {
            contents = ExcelReadWriteUtils.readExcelList(detailFile.getAbsolutePath(), 0);
        } catch (InvalidFormatException e) {
            FileUtils.writeLog(errorFilePath,"读取Excel文件异常，格式化出错。");
            e.printStackTrace();
            return retList;
        } catch (IOException e) {
            FileUtils.writeLog(errorFilePath,"读取Excel文件异常，IO异常，请检查文件是否已经打开或则被其他程序占用。");
            e.printStackTrace();
            return retList;
        }

        int count = 0;
        for (String item : contents) {
            count++;
            if (count <= 1) {
                String title = "工号,姓名,性别,电话号码,邮箱,住址,入职日期,在职状态,地域,技能,职位";
                if (!item.startsWith(title)){
                    FileUtils.writeLog(errorFilePath,"excel文件不是员工格式的文件，请严格按照如下格式制作文件：\n" +
                            title);
                    return retList;
                }
                continue;
            }

            List<String> items = Arrays.asList(item.split(","));
            if (items == null || items.size() == 0) {
                continue;
            }
            StaffInfo staff = new StaffInfo();

            staff.setId( items.get(0));
            staff.setName(items.get(1));
            staff.setSex(items.get(2));
            staff.setPhone(items.get(3));
            staff.setEmail(items.get(4));
            staff.setAddress(items.get(5));
            staff.setJoinDate(items.get(6));
            staff.setStatus(items.get(7));
            staff.setRegion(items.get(8));
            staff.setSkillType(items.get(9));
            staff.setLevel(items.get(10));

            retList.add(staff);
        }

        return retList;
    }

}
